package com.dm0858.bianmin.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.dm0858.bianmin.R;
import com.dm0858.bianmin.app.MyApp;
import com.dm0858.bianmin.mine.tools.LogUtils;
import com.dm0858.bianmin.ui.base.BaseActivity;
import com.dm0858.bianmin.ui.base.BasePresenter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import butterknife.Bind;
import cn.qqtheme.framework.picker.OptionPicker;

/**
 * Created by yyt on 2018/7/5.
 */

public class AgreementActivity extends BaseActivity {


    @Bind(R.id.oneBtn)
    ImageButton oneBtn;
    @Bind(R.id.twoBtn)
    ImageButton twoBtn;
    @Bind(R.id.threeBtn)
    ImageButton threeBtn;
    @Bind(R.id.fourBtn)
    ImageButton fourBtn;
    @Bind(R.id.OKBtn)
    Button OKBtn;
    @Bind(R.id.phoneEdit)
    EditText phoneEdit;
    @Bind(R.id.phoneOne)
    TextView phoneOne;
    @Bind(R.id.phoneTwo)
    TextView phoneTwo;
    @Bind(R.id.oneView)
    RelativeLayout oneView;
    @Bind(R.id.twoView)
    ScrollView twoView;
    @Bind(R.id.nextView)
    Button nextView;
    @Bind(R.id.okCheckBox)
    CheckBox okCheckBox;
    @Bind(R.id.industryBtn)
    Button industryBtn;
    @Bind(R.id.queryBtn)
    Button queryBtn;
    @Bind(R.id.phoneQueryEdit)
    EditText phoneQueryEdit;
    @Bind(R.id.queryRelativeLayout)
    RelativeLayout queryRelativeLayout;

    @Bind(R.id.agreementBtn)
    Button agreementBtn;
    @Bind(R.id.txt_lg_title)
    TextView txt_lg_title;
    ///查询

    private String URL =  "http://bmshfw.net/phpapi/info.php?func=checkPhone";
    private boolean btnType = false;

    private String industryType = "";
    private String industryAllStr;
    private ImageButton nowBtn;
    private boolean isCheckOk = false;
    private int twoViewIsOk = 0;
    private Bitmap oneBit;
    private Bitmap twoBit;
    private Bitmap threeBit;
    private Bitmap fourBit;
    private Thread thread;
    private File file0;
    private File file1;
    private File file2;
    private File file3;

    private ViewGroup.LayoutParams layoutParams;
    private LinearLayout mainDriverInfo;

    //private String URL =  "http://bmshfw.net/phpapi/bmahoutai/upload.php";
    private HttpUtils httpUtils;

    private String[] items = { "拍照", "相册" };
    private String title = "选择照片";
    private static final int PHOTO_CARMERA = 0;
    private static final int PHOTO_PICK = 1;
    private static final int PHOTO_CUT = 2;
    private String pic_path = "";
    List<String> mSelected;

    /**
     * 创建一个以当前系统时间为名称的文件，防止重复
     */
    private File tempFile = new File(Environment.getExternalStorageDirectory(),
            getPhotoFileName());


    /**
     * 使用系统当前日期加以调整作为照片的名称
     * @return
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("'PNG'_yyyyMMdd_HHmmss");
        return sdf.format(date) + ".png";
    }



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        // 获得Resources 实例


        Resources r = getResources();


// 通过getDimension方法获得尺寸值


        int btn_h = r.getDisplayMetrics().heightPixels;


        int btn_w = r.getDisplayMetrics().widthPixels;


        oneBtn.setMinimumHeight(btn_w);
        oneBtn.setMaxHeight(btn_w);
        ///查询




    }

    ///查询用
    private void hideKeyboard() {

        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm.isActive() && this.getCurrentFocus() != null) {

            if (this.getCurrentFocus().getWindowToken() != null) {

                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            }

        }

    }

    private void loadQuery() {
        AjaxParams params = new AjaxParams();
        params.put("phone", MyApp.phone);
        params.put("userid", MyApp.userid);



        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/info.php?func=checkPhone", params, new AjaxCallBack() {

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);

                //status

                try {

                    JSONObject json = new JSONObject(o.toString());
                    int code = 0;
                    code = json.getInt("status");
                    hideKeyboard();
                    if (code == 1) {
                        //审核通过
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                AgreementActivity.this);
                        final Dialog dialog = new Dialog(AgreementActivity.this);
                        builder.setTitle(CacheUtils.getPhone(AgreementActivity.this));
                        builder.setMessage("该手机号审核已通过，是否前往发布页面");
                        builder.setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {

                                    public void onClick(DialogInterface arg0, int arg1) {
                                        Intent intent = new Intent(AgreementActivity.this, CategoryActivity.class);
                                        startActivity(intent);
                                        dialog.dismiss();
                                    }
                                });
                        builder.setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {

                                    public void onClick(DialogInterface arg0, int arg1) {
                                        dialog.dismiss();
                                    }
                                });
                        if (isD) {
                            return;
                        }
                        builder.create().show();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);


            }
        });
    }



    private void phoneQuery() {
        //

        AjaxParams params = new AjaxParams();
        params.put("phone", MyApp.phone);
        params.put("userid",MyApp.userid);
        LogUtils.d("phone " + MyApp.phone + " userid " + MyApp.userid  );

        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/info.php?func=checkPhone", params, new AjaxCallBack() {

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                progressDialog.dismiss();
                progressDialog.setMessage("0% 正在上传...请稍后");
                //status

                try {

                    LogUtils.d(o.toString());
                    JSONObject json = new JSONObject(o.toString());
                    int code = 0;
                    code = json.getInt("status");
                    hideKeyboard();
                    if (code == 1) {
                        btnType = true;
                        queryBtn.setText("去发布信息");
                        Toast.makeText(AgreementActivity.this, "审核通过",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        btnType = false;
                        Toast.makeText(AgreementActivity.this, "审核中",
                                Toast.LENGTH_SHORT).show();
                        queryBtn.setText("查询");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                progressDialog.dismiss();

                Toast.makeText(AgreementActivity.this, "查询失败",
                        Toast.LENGTH_SHORT).show();

            }
        });

    }

    private static final int READ_PHONE_STATE =10110;

    public void showContacts(){
        if (ContextCompat.checkSelfPermission(AgreementActivity.this,
                android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED
                ||ActivityCompat.checkSelfPermission(AgreementActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                ) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, READ_PHONE_STATE);
        }else{

        }
    }



    private android.content.DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case 0:
                    // 调用拍照
                    //动态申请存储权限
                    if (ActivityCompat.checkSelfPermission(AgreementActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(AgreementActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                        Toast.makeText(AgreementActivity.this, "无权限，请手动开启存储权限",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Build.VERSION.SDK_INT>22){
                        if (ContextCompat.checkSelfPermission(AgreementActivity.this,
                                android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                            //先判断有没有权限 ，没有就在这里进行权限的申请
                            ActivityCompat.requestPermissions(AgreementActivity.this,
                                    new String[]{android.Manifest.permission.CAMERA},1);
                            Toast.makeText(AgreementActivity.this, "无权限，请手动开启拍照权限",
                                    Toast.LENGTH_SHORT).show();
                        }else {
                            //说明已经获取到摄像头权限了 想干嘛干嘛
                            photo();

                        }
                    }else {
//这个说明系统版本在6.0之下，不需要动态获取权限。
                        photo();

                    }
                    //startCamera(dialog);
                    break;
                case 1:
                    // 调用相册
                    //动态申请存储权限
                    if (ActivityCompat.checkSelfPermission(AgreementActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(AgreementActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                        Toast.makeText(AgreementActivity.this, "无权限，请手动开启存储权限",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                        startPick(dialog);



                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    @Bind(R.id.iv_back)
    ImageView iv_back;
    @Override
    public void initData() {
        super.initData();

        Resources r = getResources();


// 通过getDimension方法获得尺寸值



        initProgressDialog();

        httpUtils = new HttpUtils(10000);

        setupUI();
//2、通过Resources获取

        layoutParams = oneBtn.getLayoutParams();


        txt_lg_title.setText("查询");
//        loadQuery();
        phoneQuery();

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    //动态申请存储权限
    }



    private void saveBit(Bitmap bit){
        if (nowBtn == oneBtn) {
            oneBit = bit;
        }else if (nowBtn == twoBtn){
            twoBit = bit;
        }else if (nowBtn == threeBtn){
            threeBit = bit;
        }else {
            fourBit = bit;
        }
    }
    public void setupUI() {

        okCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isCheckOk = b;
            }
        });


        nextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCheckOk){
                    oneView.setVisibility(View.GONE);
                    queryRelativeLayout.setVisibility(View.GONE);
                    twoView.setVisibility(View.VISIBLE);
                    txt_lg_title.setText("资质文件上传");


                }else{
                    Toast.makeText(AgreementActivity.this, "请同意该协议！",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
        agreementBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showContacts();
                oneView.setVisibility(View.VISIBLE);
                queryRelativeLayout.setVisibility(View.GONE);
                twoView.setVisibility(View.GONE);
                txt_lg_title.setText("平台协议");
            }
        });

        oneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowBtn = oneBtn;
                goPicture();
//                AlertDialog.Builder dialog = AndroidUtil.getListDialogBuilder(
//                        AgreementActivity.this, items, title, dialogListener);
//                dialog.show();
            }
        });
        twoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowBtn = twoBtn;
                goPicture();
//                AlertDialog.Builder dialog = AndroidUtil.getListDialogBuilder(
//                        AgreementActivity.this, items, title, dialogListener);
//                dialog.show();
            }
        });
        threeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowBtn = threeBtn;
                goPicture();
//                AlertDialog.Builder dialog = AndroidUtil.getListDialogBuilder(
//                        AgreementActivity.this, items, title, dialogListener);
//                dialog.show();
            }
        });
        fourBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowBtn = fourBtn;
                goPicture();
//                AlertDialog.Builder dialog = AndroidUtil.getListDialogBuilder(
//                        AgreementActivity.this, items, title, dialogListener);
//                dialog.show();
            }
        });

        industryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industryAllStr = CacheUtils.getIndustry(AgreementActivity.this);
                if (industryAllStr.equals("")){
                    return;
                }else{
                    industryAll();
                }
                industryAll();
            }
        });

        OKBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (phoneEdit.getText().length() != 11){
                    Toast.makeText(AgreementActivity.this, "手机号码格式有误",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (oneBit == null ||twoBit == null ||threeBit == null ||fourBit == null){
                    Toast.makeText(AgreementActivity.this, "请将所需图片上传完整",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (industryType.equals("")){
                    Toast.makeText(AgreementActivity.this, "请选择行业",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                AjaxParams params = new AjaxParams();
                params.put("phone", String.valueOf(phoneEdit.getText()));


                FinalHttp fh = new FinalHttp();
                fh.post("http://bmshfw.net/phpapi/info.php?func=checkPhone", params, new AjaxCallBack() {

                    @Override
                    public void onSuccess(Object o) {
                        super.onSuccess(o);

                        //status

                        try {

                            JSONObject json = new JSONObject(o.toString());
                            int code = 0;
                            code = json.getInt("status");
                            hideKeyboard();
                            if (code == 1) {
                                //已经审核过，不继续申请
                                Toast.makeText(AgreementActivity.this, "该手机已经提交过申请，不能重复提交",
                                        Toast.LENGTH_SHORT).show();
                            }else {
                                progressDialog.show();
                                new Thread(new Runnable(){
                                    @Override
                                    public void run() {
                                        //在这里做耗时操作.

                                        upload();
                                    }
                                }).start();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);


                    }
                });



            }
        });

        phoneOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call("08318212072");

            }
        });

        phoneTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call("08318212072");

            }
        });

        phoneQueryEdit.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
                btnType = false;
                queryBtn.setText("查询");
            }


            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        queryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideKeyboard();
                if (btnType) {
                    //前往发布信息
                    Intent intent = new Intent(AgreementActivity.this, CategoryActivity.class);
                    startActivity(intent);
                    return;
                }
                if (phoneQueryEdit.getText().length() != 11){
                    Toast.makeText(AgreementActivity.this, "手机号码格式有误",
                            Toast.LENGTH_SHORT).show();


                    return;
                }
                progressDialog.setMessage("正在查询...请稍后");
                progressDialog.show();
                phoneQuery();
            }
        });



    }





    /***
     *  把StringJson转换为list类型
     */
    public <IndustryAll> List<com.dm0858.bianmin.ui.activity.IndustryAll> getIndustryAlls() {
        List<com.dm0858.bianmin.ui.activity.IndustryAll> datalist=new ArrayList<com.dm0858.bianmin.ui.activity.IndustryAll>();
        if (null == industryAllStr) {
            return datalist;
        }
        Gson gson = new Gson();
        datalist = gson.fromJson(industryAllStr, new TypeToken<List<com.dm0858.bianmin.ui.activity.IndustryAll>>() {
        }.getType());
        return datalist;

    }

    private void industryAll(){
        List<IndustryAll> industryAlls = getIndustryAlls();
        List<String> industryNames = new ArrayList<String>();
        for (int i = 0; i < industryAlls.size(); i++){
            industryNames.add(industryAlls.get(i).getName());
        }
        OptionPicker picker = new OptionPicker(AgreementActivity.this,industryNames);
        picker.setOffset(3);
        picker.setSelectedIndex(0);
        picker.setTextSize(15);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                IndustryAll industryAll = industryAlls.get(index);
                industryType = industryAll.getId();
                industryBtn.setText(industryAll.getName());
            }
        });
        picker.show();
    }



    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File photoFile = new File(this.getExternalCacheDir(),"output.png");
        try {
            if (photoFile.exists()){
                photoFile.delete();//删除
            }
            photoFile.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri imageuri ;
        if (Build.VERSION.SDK_INT >= 24){
            imageuri = FileProvider.getUriForFile(this,
                    "com.bmshfw.fileprovider",
                    photoFile);
        }else{
            imageuri = Uri.fromFile(photoFile);
        }
        mCutUri = imageuri;
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageuri);
        startActivityForResult(openCameraIntent, PHOTO_CARMERA);
    }


    private Uri mCutUri;


    /**
     * 调用系统相册
     * @param dialog
     */
    protected void startPick(DialogInterface dialog) {
        System.out.println("file1:");

        Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image/*"); // 设置文件类型
        intentFromGallery
                .setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery,
                PHOTO_PICK);
        dialog.dismiss();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_CHOOSE) {
            if (data == null) {
                return;
            }

            mSelected = Matisse.obtainPathResult(data);
            Log.d("Matisse", "mSelected: " + mSelected);

            for (int i = 0; i < mSelected.size();i++) {
                // 读取uri所在的图片


                progressDialogTwo.show();
                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        //在这里做耗时操作.

                            String path = amendRotatePhoto(Matisse.obtainPathResult(data).get(0));


                            Bitmap pickBm =  BitmapFactory.decodeFile(path);
                            AgreementActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) nowBtn.getLayoutParams();

                                    // 取控件aaa当前的布局参数
                                    int height = (int) (nowBtn.getWidth() * 0.8);

                                    linearParams.height = linearParams.width - height; // 当控件的高强制设成宽度

                                    nowBtn.setLayoutParams(linearParams);


                                    nowBtn.setImageBitmap(zoomBitmap(pickBm, nowBtn.getWidth(), height));
                                    progressDialogTwo.dismiss();
                                }
                            });
                            saveBit(pickBm);

                    }
                }).start();

            }





        }


    }

    public static Uri getImageContentUri(Context context, java.io.File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }

        }

    }


            /**
             * @param bitmap 对象
             * @param w 要缩放的宽度
             * @param h 要缩放的高度
             * @return newBmp 新 Bitmap对象
             */
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newBmp;
    }


    /**
     * 把batmap 转file
     * @param bitmap
     * @param filepath
     */
    public  File saveBitmapFile(Bitmap bitmap, String filepath) {
        File file = new File(filepath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public File compressImage(Bitmap bitmap,int i) {
        int abc = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 50;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
            abc++;
            Log.v("------------------",""+abc);
        }
        String name = "";
        switch (i){
            case 0:
                name = "cardfront";
                break;
            case 1:
                name = "cardbehind";
                break;
            case 2:
                name = "licencepic";
                break;
            case 3:
                name = "certificate";
                break;
        }
        File file = new File(Environment.getExternalStorageDirectory(),""+String.valueOf(phoneEdit.getText())+name+".jpeg");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        AgreementActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (i == 3){
                    progressDialog.setMessage( "99% 正在上传...请稍后");

                }else {
                    progressDialog.setMessage( (i+1) * 25 + "% 正在上传...请稍后");
                }
            }
        });
        return file;
    }





    /**
     * 上传文件到服务器
     */
    protected void upload() {

        AjaxParams params = new AjaxParams();
        try {
            params.put("file0", compressImage(oneBit,0));
            params.put("file1", compressImage(twoBit,1));
            params.put("file2", compressImage(threeBit,2));
            params.put("file3", compressImage(fourBit,3));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

//        params.put("phone", String.valueOf(phoneEdit.getText()));
//        params.put("type", industryType);


        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/bmahoutai/upload.php", params, new AjaxCallBack(){
            @Override
            public void onLoading(long count, long current) {

                Log.v("dddddd","正在上传");

            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Gson gson = new Gson();
                HttpFile file = gson.fromJson((String) o, HttpFile.class);
                getHttp(file);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                progressDialog.dismiss();
                Toast.makeText(AgreementActivity.this, "上传失败",
                        Toast.LENGTH_SHORT).show();
                Log.v("dabadbd","上传NO");
                progressDialog.setMessage("0% 正在上传...请稍后");

            }
        });

    }
    /**
     * 上传文件到服务器
     */
    protected void getHttp(HttpFile file) {

        AjaxParams params = new AjaxParams();
        params.put("cardfront", file.getFile0());
        params.put("cardbehind", file.getFile1());
        params.put("licencepic", file.getFile2());
        params.put("certificate", file.getFile3());
        params.put("phone", String.valueOf(phoneEdit.getText()));
        params.put("type", industryType);


        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/info.php?func=submitProvider", params, new AjaxCallBack(){


            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                progressDialog.dismiss();
                Toast.makeText(AgreementActivity.this, "上传成功",
                        Toast.LENGTH_SHORT).show();
                Log.v("dasddd","上传完成");
                progressDialog.setMessage("0% 正在上传...请稍后");
                CacheUtils.setPhone(AgreementActivity.this, String.valueOf(phoneEdit.getText()));

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                progressDialog.dismiss();
                Toast.makeText(AgreementActivity.this, "上传失败",
                        Toast.LENGTH_SHORT).show();
                Log.v("dabadbd","上传NO");
                progressDialog.setMessage("0% 正在上传...请稍后");

            }
        });

    }

    /**
     * 调用拨号界面
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_agreement;
    }



    private ProgressDialog progressDialog;
    private ProgressDialog progressDialogTwo;
    private void initProgressDialog() {
        progressDialog = new ProgressDialog(AgreementActivity.this);
        progressDialog.setIndeterminate(false);//循环滚动
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("0% 正在上传...请稍后");
        progressDialog.setCancelable(false);//false不能取消显示，true可以取消显示
        progressDialogTwo = new ProgressDialog(AgreementActivity.this);
        progressDialogTwo.setIndeterminate(false);//循环滚动
        progressDialogTwo.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialogTwo.setMessage("正在加载中...");
        progressDialogTwo.setCancelable(false);//false不能取消显示，true可以取消显示
    }




    private static final int REQUEST_CODE_CHOOSE = 10087;//定义请求码常量

    //选取照片模块
    private void goPicture(){
        //动态申请存储权限
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                ) {
            Toast.makeText(this, "无权限，请手动开启拍照存储权限",
                    Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, READ_PHONE_STATE);
            return;
        }
        // 进入相册
        int index = 1;
        Matisse.from(AgreementActivity.this)
                .choose(MimeType.ofImage(), false) // 选择 mime 的类型
                .countable(true)
                .capture(true)
                .captureStrategy(
                        new CaptureStrategy(true, "com.bmshfw.fileprovider"))
                .maxSelectable(index) // 图片选择的最多数量
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new PicassoEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码



    }



    /**
     * 处理旋转后的图片
     * @param path 原图路径
     * @return 返回修复完毕后的图片路径
     */
    public String amendRotatePhoto(String path) {

        // 取得图片旋转角度
        int angle = readPictureDegree(path);
        if (angle == 0) {
            return path;
        }
        // 把原图压缩后得到Bitmap对象
        Bitmap bmp = BitmapFactory.decodeFile(path);
        // 修复图片被旋转的角度
        Bitmap bitmap = rotaingImageView(angle, bmp);

        // 保存修复后的图片并返回保存后的图片路径
        return savePhotoToSD(bitmap, this);
    }

    /**
     * 把原图按1/10的比例压缩
     *
     * @param path 原图的路径
     * @return 压缩后的图片
     */
    public static Bitmap getCompressPhoto(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 10;  // 图片的大小设置为原来的十分之一
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        options = null;
        return bmp;
    }

    /**
     * 读取照片旋转角度
     *
     * @param path 照片路径
     * @return 角度
     */
    public  int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 保存Bitmap图片在SD卡中
     * 如果没有SD卡则存在手机中
     *
     * @param mbitmap 需要保存的Bitmap图片
     * @return 保存成功时返回图片的路径，失败时返回null
     */
    public  String savePhotoToSD(Bitmap mbitmap, Context context) {
        FileOutputStream outStream = null;
        String fileName = getPhotoFileName(context);
        try {
            outStream = new FileOutputStream(fileName);
            // 把数据写入文件，100表示不压缩
            mbitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (outStream != null) {
                    // 记得要关闭流！
                    outStream.close();
                }
                if (mbitmap != null) {
                    mbitmap.recycle();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isD = true;
    }

    private boolean isD = false;
    /**
     * 存放拍摄图片的文件夹
     */
    private  final String FILES_NAME = "/MyPhoto";
    /**
     * 获取的时间格式
     */
    public  final String TIME_STYLE = "yyyyMMddHHmmss";
    /**
     * 图片种类
     */
    public  final String IMAGE_TYPE = ".png";


    /**
     * 获取手机可存储路径
     *
     * @param context 上下文
     * @return 手机可存储路径
     */
    private  String getPhoneRootPath(Context context) {
        // 是否有SD卡
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || !Environment.isExternalStorageRemovable()) {
            // 获取SD卡根目录
            return context.getExternalCacheDir().getPath();
        } else {
            // 获取apk包下的缓存路径
            return context.getCacheDir().getPath();
        }
    }

    /**
     * 使用当前系统时间作为上传图片的名称
     *
     * @return 存储的根路径+图片名称
     */
    public  String getPhotoFileName(Context context) {
        File file = new File(getPhoneRootPath(context) + FILES_NAME);
        // 判断文件是否已经存在，不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        // 设置图片文件名称
        SimpleDateFormat format = new SimpleDateFormat(TIME_STYLE, Locale.getDefault());
        Date date = new Date(System.currentTimeMillis());
        String time = format.format(date);
        String photoName = "/" + time + IMAGE_TYPE;
        return file + photoName;
    }

    /**
     * 旋转图片
     * @param angle 被旋转角度
     * @param bitmap 图片对象
     * @return 旋转后的图片
     */
    public  Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }

}




